package svg.hw.app;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

import java.io.*;
import java.util.*;

import svg.hw.quiz.*;
import svg.hw.recog.*;
import java.text.NumberFormat;
import java.text.DecimalFormat;


public class MainEntry extends JDialog {

    /**
     * The downsample width for the application.
     */
    public static final int DOWNSAMPLE_WIDTH = 16;

    /**
     * The down sample height for the application.
     */
    public static final int DOWNSAMPLE_HEIGHT = 16;

    QuizCanvas qc;
    DigitizerPanel dg;
    JTextArea textArea;
    JComboBox cboLetter;

    NumberFormat nf = new DecimalFormat("#.##");

    protected static final String[] letters = {"a","aa","i","ii","u","uu","ksha","e","ai","o","au","am","ah", "ka","kha","ga","gha","cha","chah","ja","jha","naah","ta","tha","da","dha","nah","tah","thah","dah","dhah","na","pa","pha","ba", "bha","ma","yah","ra","la","va","sah","sha","sa","ha","ksa","tra","jna","sra"};
    private Hashtable data;

    public MainEntry(Frame owner, Hashtable data) {
        super(owner, "Quiz", true);
        this.data = data;
        Container container = getContentPane();
        container.add(createTopPanel(), BorderLayout.NORTH);
        container.add(createCenterPanel(), BorderLayout.CENTER);
        container.add(createButtonPanel(), BorderLayout.SOUTH);
    }

    public JPanel createTopPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));

        JLabel lblLetter = new JLabel("Select a letter that you want to draw");
        panel.add(lblLetter);

        cboLetter = new JComboBox(letters);
        panel.add(cboLetter);

        return panel;
    }

    public JPanel createCenterPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        JPanel centerTopPanel = new JPanel(new GridLayout(1,1));
        qc = new QuizCanvas();
        centerTopPanel.add(qc);

        dg = new DigitizerPanel();
        dg.setSampleWidth(DOWNSAMPLE_WIDTH);
        dg.setSampleHeight(DOWNSAMPLE_HEIGHT);
        //centerTopPanel.add(dg);


        JPanel centerBottomPanel = new JPanel(new BorderLayout());
        textArea = new JTextArea();
        textArea.setFont(new Font("QuizDialog", Font.PLAIN, 11));
        JScrollPane scrollPane =
            new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.getViewport().add(textArea);
        centerBottomPanel.add(scrollPane, BorderLayout.CENTER);

        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setTopComponent(centerTopPanel);
        splitPane.setBottomComponent(centerBottomPanel);
        splitPane.setDividerSize(6);
        splitPane.setResizeWeight(0.75);

        panel.add(splitPane);

        return panel;
    }


    public JPanel createButtonPanel() {
        JPanel btnPanel = new JPanel();

/*        JButton btnDigitize = new JButton("Digitize");
        btnDigitize.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                digitize();
            }
        });
        btnPanel.add(btnDigitize);
*/

        JButton btnRecognize = new JButton("Recognize");
        btnRecognize.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	digitize();
            	recognize();
            }
        });
        btnPanel.add(btnRecognize);

        JButton btnClear = new JButton("Clear");
        btnClear.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                clear();
            }
        });
        btnPanel.add(btnClear);

/*		JButton btnPixelize = new JButton("Pixelize");
        btnPixelize.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                pixelize();
            }
        });
        btnPanel.add(btnPixelize);
*/
        return btnPanel;
    }

    private void pixelize() {
        String pixels = getPixelGrid(dg.getSample());
        textArea.setText(pixels);
    }

    private void clear() {
        qc.clear();
        dg.setSample(null);
        textArea.setText("");
    }

    public void digitize() {
        ImageData data = qc.getPixels(DOWNSAMPLE_WIDTH, DOWNSAMPLE_HEIGHT);
        DownSampler ds = new DownSampler(DOWNSAMPLE_WIDTH, DOWNSAMPLE_HEIGHT);
        ImageData dsdat = ds.downSample(data);
        dg.setSample(dsdat);
    }

    public void recognize() {
        textArea.setText("");

        ImageData drawn = dg.getSample();
        float result = 0;

        String letter = (String)cboLetter.getSelectedItem();
        Object val = data.get(letter);

        ImageData dat = (ImageData) val;

        for (int y = 0; y < dat.getHeight(); y++) {
            for (int x = 0; x < dat.getWidth(); x++) {
                int template = dat.getData(x, y);
                if (drawn.getData(x,y) == 0) {
                    template = template * -1;
                }
                result = result + template;
            }
        }

        result = 100 * result / (float)(DOWNSAMPLE_WIDTH * DOWNSAMPLE_HEIGHT);
        String percent = nf.format(result);
        //gives rounding of the percent of the character correct

        //System.out.println(key + " = " + result);
        textArea.setText(textArea.getText() + letter + " = " + percent + "%\n");
    }

    //temporary change to see if it can be integrated with svg application
 /*   public static void main(String[] args) {
        Hashtable data = load("./hindi16x16.txt");
        MainEntry me = new MainEntry(data);
        me.setSize(450, 350);
        me.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        centerWindow(me);
        me.show();
    }

*/

    /*
    public static Hashtable load(String fileName) {
        Hashtable table = new Hashtable();
        try {
            FileReader f; // the actual file stream
            BufferedReader r; // used to read the file line by line

            f = new FileReader(fileName);
            r = new BufferedReader(f);
            String line;
            int y = 0;

            String letter = null;
            ImageData dat = null;
            while ((line = r.readLine()) != null) {
                if (line.trim().length() == 0) {
                    continue;
                }

                if (line.endsWith(":")) {
                    letter = line.substring(0, line.length()-1);
                    dat =
                        new ImageData(DOWNSAMPLE_WIDTH,
                                      DOWNSAMPLE_HEIGHT);
                    table.put(letter, dat);
                    y = 0;
                    continue;
                }

                String[] weights = line.split(",");
                for (int i = 0; i < weights.length; i++) {
                    String weight = weights[i].trim();
                    int w = Integer.parseInt(weight);
                    dat.setData(i, y, w);
                }

                y = y + 1;
            }

            r.close();
            f.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }
*/

    String getPixelGrid(ImageData data) {
        StringBuffer buf = new StringBuffer();
        for (int y = 0; y < data.getHeight(); y++) {
            for (int x = 0; x < data.getWidth(); x++) {
                int pixel = data.getData(x, y);
                pixel = (pixel == 0) ? -1 : pixel;
                if (pixel > 0) {
                    buf.append(" ").append(pixel);
                }
                else {
                    buf.append(pixel);
                }

                if (x < data.getWidth() -1)
                    buf.append(", ");
            }
            buf.append("\n");
        }
        return buf.toString();
    }

    /**
     * Makes the dialog centered on the screen
     * @param dialog Dialog the dialog
     */
  /*  public static void centerWindow(Window window) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension windowSize = window.getSize();
        window.setLocation((screenSize.width - windowSize.width) / 2,
                           (screenSize.height - windowSize.height) / 2);
    };*/
}
